package org.fitweb.examples;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.IOUtils;
import org.fitweb.ExtensionPoint;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;

import static java.util.concurrent.Executors.*;

public class MinimalWebServer implements HttpHandler {

    public String requestBody;
    public Headers headers;
    public String method;
    public URI uri;
    public int port;
    private HttpServer server;

    public MinimalWebServer(int port) {
        this.port = port;
        server = createOn(port);
        server.createContext("/", this);
        server.setExecutor(newSingleThreadExecutor());
        server.start();
    }

    public void stop() {
        server.stop(0);
    }

    private HttpServer createOn(int port) {
        try {
            return HttpServer.create(new InetSocketAddress(port), 1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        requestBody = IOUtils.toString(httpExchange.getRequestBody());
        headers = httpExchange.getRequestHeaders();
        method = httpExchange.getRequestMethod();
        uri = httpExchange.getRequestURI();

        writeResponse(httpExchange, generateResponse());
    }

    @ExtensionPoint
    protected String generateResponse() {
        StringBuilder buffy = new StringBuilder("<html><body><pre>Request Headers:\n");
        for (String header : headers.keySet()) {
            buffy.append(header).append(": ").append(headers.get(header)).append("\n");
        }
        buffy.append("</pre></body></html>");
        return buffy.toString();
    }

    private void writeResponse(HttpExchange httpExchange, String response) throws IOException {
        httpExchange.getResponseHeaders().add("Content-Type", "text/html");
        httpExchange.sendResponseHeaders(200, response.length());
        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}
